package com.asktgapp.engineer.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.engineer.activity.SetWithDrawPwdActivity;
import com.asktgapp.model.CodeVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.utils.MCountDownTimer;
import com.asktgapp.modulebase.common.util.Util;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/18
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:5.9.3首次修改（即设置）提现密码时身份验证
 */

public class IDVerificationFragment extends BaseFragment {
    @InjectView(R.id.et_varification_id)
    EditText mIDCardEt;
    @InjectView(R.id.et_varification_code)
    EditText mCodeEt;
    @InjectView(R.id.tv_varification_send_code)
    TextView mSendCodeTv;
    @InjectView(R.id.tv_varification_send_next)
    TextView mNextTv;
    private TimeCount timeCount;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_id_varification, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mSendCodeTv.setOnClickListener(this);
        mNextTv.setOnClickListener(this);
        timeCount = new TimeCount(60000, 1000);

    }

    @Override
    public void loadData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_varification_send_code:
                sendCode();
                break;
            case R.id.tv_varification_send_next:
                String idCard = mIDCardEt.getText().toString().trim();
                String code = mCodeEt.getText().toString().trim();
                doNext(idCard, code);
                break;
        }
    }

    private void doNext(String idCard, String code) {
        if (Util.isEmpty(idCard)) {
            showTost("请输入身份证号码！", 0);
            return;
        }
        if (!Util.doAuthentication(idCard)) {
            showTost("请输入合法的身份证格式！", 0);
            return;
        }
        if (Util.isEmpty(code)) {
            showTost("请输入验证码!", 0);
            return;
        }
        final Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("type", 3);
        params.put("cardNo", idCard);
        params.put("code", code);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.updateNick(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    Intent intent = new Intent(getActivity(), SetWithDrawPwdActivity.class);
                    intent.putExtra("flag", 2);
                    startActivity(intent);
                    getActivity().finish();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 1);
                }
            }
        });

    }

    private void sendCode() {
        hideSoftKeyboard();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("phone", PreferencesUtil.getString(getActivity(), PreferencesUtil.KEY_PHONE));
        params.put("type", 1);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<CodeVO>> call = apiservice.sendCode(params);
        call.enqueue(new Callback<ApiResponseBody<CodeVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<CodeVO>> call, Response<ApiResponseBody<CodeVO>> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    CodeVO bean = response.body().getResult();
//                    mCodeEt.setText(String.valueOf(bean.getCode()));
                    showTost("验证码已发送", 1);
                    timeCount.start();
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<CodeVO>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });


    }

    class TimeCount extends MCountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (mSendCodeTv == null)
                return;

            mSendCodeTv.setText("发送验证码");
            // mSendCode.setTextColor(Color.parseColor("#40a540"));
            mSendCodeTv.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            if (mSendCodeTv == null)
                return;
            mSendCodeTv.setClickable(false);
            mSendCodeTv.setText(millisUntilFinished / 1000 + "秒后重发");
        }
    }
}
